package sync;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import model.Container;
import model.Playlist;
import model.PlaylistRecord;
import model.contents.Content;
import net.HttpRequestFacade;

import org.json.simple.JSONObject;

public class PlayerUpdateSynchronizer {

	private JSONObject data;

	public PlayerUpdateSynchronizer() {
		this.data = new JSONObject();
	}

	private void put(String key, List<Integer> list) {
		if (list == null || list.size() <= 0) {
			return;
		}
		data.put(key, list);
	}

	public void addPlaylistIDs(List<Playlist> playlists) {
		List<Integer> playlistIDs = new ArrayList<Integer>();
		for (Playlist p : playlists) {
			playlistIDs.add(p.getId());
		}
		this.put("Playlist", playlistIDs);
	}

	public void addContentIDs(List<Content> contents) {
		List<Integer> contentIDs = new ArrayList<Integer>();
		for (Content c : contents) {
			contentIDs.add(c.getId());
		}
		this.put("Content", contentIDs);
	}

	public void addContainerIDs(List<Container> containers) {
		List<Integer> containerIDs = new ArrayList<Integer>();
		for (Container c : containers) {
			containerIDs.add(c.getId());
		}
		this.put("Container", containerIDs);
	}

	public void addPlaylistRecordIDs(List<PlaylistRecord> records) {
		List<Integer> containerIDs = new ArrayList<Integer>();
		for (PlaylistRecord record : records) {
			containerIDs.add(record.getId());
		}
		this.put("PlaylistRecord", containerIDs);
	}

	public String toString() {
		return data.toJSONString();
	}

	private String getEncodedString() {
		return data.toJSONString();
	}

	public void send() {
		Thread synchronizerThread = new Thread(new Runnable() {

			@Override
			public void run() {
				Map<String, String> data = new HashMap<String, String>();
				data.put("updatedContents", PlayerUpdateSynchronizer.this.getEncodedString());
				HttpRequestFacade.sendToPlayerUpdatePage(data);
			}
		});
		synchronizerThread.setName("Player update synchronizer thread");
		synchronizerThread.start();
	}
}
